<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="title">用户注册</h2>
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        class="register-form"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
          />
        </el-form-item>

        <el-form-item prop="imageCode">
          <el-input
            v-model="registerForm.imageCode"
            placeholder="请输入图片验证码"
            prefix-icon="el-icon-edit"
            :disabled="!uuid"
          >
            <template #suffix>
              <img
                class="image-code"
                :src="imageCodeUrl"
                @click="refreshImageCode"
                alt="图片验证码"
              />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="smsCode">
          <el-input
            v-model="registerForm.smsCode"
            placeholder="请输入短信验证码"
            prefix-icon="el-icon-key"
            :disabled="countdown < 0"
          >
            <template #append>
              <el-button
                :disabled="countdown.value > 0 || !registerForm.phone || !registerForm.imageCode"
                @click="sendSmsCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取短信验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            prefix-icon="el-icon-lock"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleRegister"
            class="register-btn"
            :loading="isLoading"
          >
            {{ isLoading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-link">
        已有账号？<el-link type="primary" @click="goToLogin">前往登录</el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const uuid = ref('');
const countdown = ref(0);
const isLoading = ref(false);

// 注册表单数据
const registerForm = reactive({
  phone: '',
  imageCode: '',
  smsCode: '',
  password: ''
});

// 表单校验规则
const registerRules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  imageCode: [{ required: true, message: '请输入图片验证码', trigger: 'blur' }],
  smsCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需6-20位', trigger: 'blur' }
  ]
});

// 图片验证码URL
const imageCodeUrl = ref('');

// 初始化UUID和图片验证码
onMounted(() => {
  generateUuid();
  refreshImageCode();
});

// 生成UUID
const generateUuid = () => {
  uuid.value = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};

// 刷新图片验证码
const refreshImageCode = () => {
  generateUuid();
  imageCodeUrl.value = `http://127.0.0.1:8000/users/imagecode/?uuid=${uuid.value}`;
};

// 发送短信验证码
const sendSmsCode = async () => {
  try {
    const { data } = await axios.post('http://127.0.0.1:8000/users/send_code/', {
      phone: registerForm.phone,
      imagecode: registerForm.imageCode,
      uuid: uuid.value
    });

    if (data.code === 200) {
      ElMessage.success('短信验证码发送成功');
      startCountdown();
    } else {
      ElMessage.error(data.msg);
      refreshImageCode(); // 错误后刷新图片验证码
    }
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试');
    console.error(error);
  }
};

// 倒计时逻辑
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value < 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 注册处理
const handleRegister = async () => {
  isLoading.value = true;
  try {
    const { data } = await axios.post('http://127.0.0.1:8000/users/register/', {
      phone: registerForm.phone,
      code: registerForm.smsCode,
      password: registerForm.password
    });

    if (data.code === 200) {
      ElMessage.success('注册成功！请登录');
      router.push('/login'); // 注册成功跳转登录页面
    } else if (data.msg === '用户已存在') {
      ElMessageBox.confirm(
        '用户已存在，是否前往登录？',
        '提示',
        {
          confirmButtonText: '前往登录',
          cancelButtonText: '重新注册',
          type: 'warning'
        }
      ).then(() => {
        router.push('/login');
      });
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error('注册失败，请检查信息是否正确');
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

// 跳转登录页面
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.register-card {
  width: 400px;
  padding: 30px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
}

.register-form {
  width: 100%;
}

.el-input {
  margin-bottom: 15px;
}

.image-code {
  width: 120px;
  height: 40px;
  margin-left: 10px;
  vertical-align: middle;
  cursor: pointer;
}

.register-btn {
  width: 100%;
  margin-top: 20px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}
</style>